package com.iwinding.ladygg.ui.act;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.event.BaseEvent;
import com.iwinding.ladygg.event.EventType;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.LoginCallback;
import com.iwinding.ladygg.net.callback.ThirdPartyLoginCallback;
import com.iwinding.ladygg.net.request.LoginReq;
import com.iwinding.ladygg.net.request.ThirdPartyLoginReq;
import com.iwinding.ladygg.net.response.LoginRp;
import com.iwinding.ladygg.net.response.ThirdPartyLoginRp;
import com.iwinding.ladygg.ui.auth.QQAuthApi;
import com.iwinding.ladygg.ui.auth.WeiboAuthApi;
import com.iwinding.ladygg.ui.view.ProDialogCreator;
import com.iwinding.ladygg.utils.GsonUtil;
import com.iwinding.ladygg.utils.SPUtils;
import com.iwinding.ladygg.utils.StringUtil;
import com.iwinding.ladygg.utils.ToastUtil;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.tencent.tauth.Tencent;
import com.yayandroid.theactivitymanager.TheActivityManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;


/**
 * Created by hezhiyong on 2017/3/31.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {


    private LoginType loginType = LoginType.LOGIN;

    private AutoCompleteTextView mEtPhone;
    private AutoCompleteTextView mEtPassword;//密码

    private ImageView mImgCleanPhone;
    private ImageView mImgCleanPassword;
    private ImageView mImgSecure;
    private ImageView mImgVisable;

    private Button mBtnLogin;
    private TextView mTvRegister;
    private TextView mTvForgetPw;
    private ImageView mLoginQQ;
    private ImageView mLoginSina;

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_login;
    }

    @Subscribe
    public void onEvent(BaseEvent event) {
        if (event.type == EventType.ACTIVITY_FINSH_LOGIN) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        boolean is_exit = SPUtils.getSpPropertyBoolean(this, SPConstant.IS_EXIT, false);
        boolean is_token_expired = SPUtils.getSpPropertyBoolean(this, SPConstant.IS_TOKEN_EXPIRED, false);
        if (is_exit || is_token_expired) {
            TheActivityManager.getInstance().finishAll();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBack.setVisibility(View.INVISIBLE);
        TheActivityManager.getInstance().finishInstance(MainActivity.class);
        EventBus.getDefault().register(this);
        initView();
        setListener();
    }

    void initView() {
        setTitleResId(R.string.icane_user_login);

        mEtPhone = (AutoCompleteTextView) findViewById(R.id.icane_edit_phone);
        mEtPassword = (AutoCompleteTextView) findViewById(R.id.icane_edit_pw);

        mImgCleanPhone = (ImageView) findViewById(R.id.clear_phone);
        mImgCleanPassword = (ImageView) findViewById(R.id.clear_password);
        mImgSecure = (ImageView) findViewById(R.id.icane_secure);
        mImgVisable = (ImageView) findViewById(R.id.icane_visable);

        mBtnLogin = (Button) findViewById(R.id.icane_login);
        mTvRegister = (TextView) findViewById(R.id.icane_register);
        mTvForgetPw = (TextView) findViewById(R.id.icane_forget_passward);

        mLoginQQ = (ImageView) findViewById(R.id.icane_login_qq);
        mLoginSina = (ImageView) findViewById(R.id.icane_login_weibo);

        WeiboAuthApi.getInstance().initContext(this);
        WeiboAuthApi.getInstance().initAuth();
        QQAuthApi.getInstance().initContext(this);
        QQAuthApi.getInstance().initAuth();
    }

    void setListener() {
        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mImgCleanPhone.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });
        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mImgCleanPassword.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });

        mImgCleanPhone.setOnClickListener(this);
        mImgCleanPassword.setOnClickListener(this);
        mImgSecure.setOnClickListener(this);
        mImgVisable.setOnClickListener(this);

        mBtnLogin.setOnClickListener(this);
        mTvRegister.setOnClickListener(this);
        mTvForgetPw.setOnClickListener(this);
        mLoginQQ.setOnClickListener(this);
        mLoginSina.setOnClickListener(this);


        WeiboAuthApi.getInstance().setWeiboAuthLogin(new WeiboAuthApi.WeiboAuthLogin() {
            @Override
            public void onAuth(Oauth2AccessToken mAccessToken) {
                //微博登录成功
                final String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                        new java.util.Date(mAccessToken.getExpiresTime()));
                final String token = mAccessToken.getUid();
                ThirdPartyLoginReq thirdPartyLoginReq = new ThirdPartyLoginReq();
                thirdPartyLoginReq.openId = token;
                RequestManager.postThirdPartyLogin(mContext, thirdPartyLoginReq, new ThirdPartyLoginCallback(mContext) {
                    @Override
                    public void onResult(final ThirdPartyLoginRp thirdPartyLoginRp) {
                        thirdPartyLoginRp.weiboToken = token;
                        thirdPartyLoginRp.weiboTokenDate = date;
                        saveLoginInfo(thirdPartyLoginRp);
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
                    }
                });
            }
        });

        QQAuthApi.getInstance().setQQAuthLogin(new QQAuthApi.QQAuthLogin() {
            @Override
            public void onAuth(Tencent mTencent, final String imgUrl, final String nickname) {
                final String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                        new java.util.Date(mTencent.getExpiresIn()));
                final String token = mTencent.getOpenId();
                ThirdPartyLoginReq thirdPartyLoginReq = new ThirdPartyLoginReq();
                thirdPartyLoginReq.openId = token;
                RequestManager.postThirdPartyLogin(mContext, thirdPartyLoginReq, new ThirdPartyLoginCallback(mContext) {
                    @Override
                    public void onResult(final ThirdPartyLoginRp thirdPartyLoginRp) {
                        thirdPartyLoginRp.qqToken = token;
                        thirdPartyLoginRp.qqTokenDate = date;
                        thirdPartyLoginRp.headImg = imgUrl;
                        thirdPartyLoginRp.nickName = nickname;
                        saveLoginInfo(thirdPartyLoginRp);
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
                    }
                });
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clear_phone:
                mEtPhone.setText("");
                break;
            case R.id.clear_password:
                mEtPassword.setText("");
                break;
            case R.id.icane_secure:
                mImgSecure.setVisibility(View.GONE);
                mImgVisable.setVisibility(View.VISIBLE);
                //默认状态显示密码--设置文本 要一起写才能起作用  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
//                String pw =  mEtPassword.getText().toString();
//                mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//                mEtPassword.setText(pw);
                mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                mEtPassword.setSelection(mEtPassword.getText().length());
                break;
            case R.id.icane_visable:
                mImgVisable.setVisibility(View.GONE);
                mImgSecure.setVisibility(View.VISIBLE);
//                String pwSecure =  mEtPassword.getText().toString();
//                mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//                mEtPassword.setText(pwSecure);
                mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                mEtPassword.setSelection(mEtPassword.getText().length());
                break;
            case R.id.icane_login:
                loginType = LoginType.LOGIN;
                login();
                break;
            case R.id.icane_register:
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.icane_forget_passward:
                Intent intent2 = new Intent(this, ForgetPwActivity.class);
                startActivity(intent2);
                break;
            case R.id.icane_login_qq:
                loginType = LoginType.QQAUTH;
                QQAuthApi.getInstance().login();
                break;
            case R.id.icane_login_weibo:
                loginType = LoginType.WEIBOAUTH;
                WeiboAuthApi.getInstance().authorize();
                break;
        }
    }


    /**
     * 登录
     */
    void login() {
        final LoginReq loginReq = new LoginReq();
        String phone = mEtPhone.getEditableText().toString();
        String pw = mEtPassword.getEditableText().toString();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.openEmptyPhone(this);
            return;
        }
        if (!StringUtil.isMobileNO(phone)) {
            ToastUtil.openMolieErrorToast(this);
            return;
        }
        if (TextUtils.isEmpty(pw)) {
            ToastUtil.openEmptyPw(this);
            return;
        }
        loginReq.uname = phone;
        loginReq.password = pw;

        ProDialogCreator.getInstance().showDialog("Loading...");
        RequestManager.postLogin(mContext, loginReq, new LoginCallback(LoginActivity.this) {
            @Override
            public void onResult(final LoginRp loginRp) {
                saveLoginInfo(loginRp);
            }

            @Override
            public void onFail(String errorMsg) {
                ProDialogCreator.getInstance().dismissDialog();
                ToastUtil.openBaseToast(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }

    void saveLoginInfo(LoginRp loginRp) {
        switch (loginType) {
            case QQAUTH:
            case WEIBOAUTH:
                ThirdPartyLoginRp thirdPartyLoginRp = (ThirdPartyLoginRp) loginRp;
                mOAAplication.setmLoginRp(thirdPartyLoginRp);
                break;
            case LOGIN:
                loginRp.passwrod = mEtPassword.getEditableText().toString();
                mOAAplication.setmLoginRp(loginRp);
                break;
        }
        SPUtils.putSpProperty(mContext, SPConstant.IS_EXIT, false);
        SPUtils.putSpProperty(mContext, SPConstant.LOGIN_USER, GsonUtil.getInstance().toJson(loginRp));
        loginEM(loginRp);
    }

    void loginEM(final LoginRp loginRp) {
        if (!TextUtils.isEmpty(loginRp.userId)) {
            EMClient.getInstance().login(loginRp.userId, loginRp.passwrod, new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    ProDialogCreator.getInstance().dismissDialog();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();
                        }
                    }).start();
                    if (!TextUtils.isEmpty(loginRp.isBindingPhone) && TextUtils.equals(loginRp.isBindingPhone, "0")) {
                        startActivity(new Intent(mContext, BindPhoneActivity.class));
                        return;
                    }
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                    ProDialogCreator.getInstance().dismissDialog();
                    if (code == 200) {
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }
                }
            });
            ToastUtil.openLoginSucess(LoginActivity.this);
        }else{
            ProDialogCreator.getInstance().dismissDialog();
        }
    }


    /**
     * 当 SSO 授权 Activity 退出时，该函数被调用。
     *
     * @see {@link Activity#onActivityResult}
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // SSO 授权回调
        // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResults
        WeiboAuthApi.getInstance().onActivityResult(requestCode, resultCode, data);
        QQAuthApi.getInstance().onActivityResult(requestCode, resultCode, data);
    }

    enum LoginType {
        LOGIN, WEIBOAUTH, QQAUTH
    }

}
